<?php
defined('SYSPATH') or die('No direct script access.') ;


class Cli_Trade extends CLI
{
	public function main()
	{
	    $select = DB::select(array(DB::expr('COUNT(*)'),'c'), 'buyer_id', 'goods_id','nickname')
			->from("order_rates")
			->where("buyer_flag", '=', 1)
			->where("sys", "=", 0)
			->group_by('buyer_id', 'goods_id');

		$iterator = new Db_Iterator($select, 'default', 10);

		$i = 0;

		while ($iterator->valid())
		{
			foreach ($iterator->current() as $g)
			{
				//查找order_trades表是否有记录
				$count = DB::select()
					->from("order_trades")
					->where("member_id", '=', $g['buyer_id'])
					->where("goods_id", '=', $g['goods_id'])
					->count_all();

				if($count<$g['c'])
				{
					//少记录补上
					//查找订单商品
					$order_goods_array = DB::select("og.*",'o.is_anonymity','o.pay_time')
						->from(array("order_goods", "og"))
						->join(array("orders", "o"))
						->on("o.order_id", '=', 'og.order_id')
						->where('o.member_id', '=', $g['buyer_id'])
						->where('og.goods_id', '=', $g['goods_id'])
						->fetch_all();
					$j = 0;
					foreach($order_goods_array as $order_goods)
					{
						if($j==($g['c']-$count))
						{
							break;
						}
						//插入交易记录
						$insert = array(
							'member_id'=>$g['buyer_id'],
							'nickname'=>$g['nickname'],
							'goods_id'=>$g['goods_id'],
							'goods_title'=>$order_goods['goods_title'],
							'prop_str'=>$order_goods['prop_str'],
							'original_price'=>$order_goods['original_price'],
							'price'=>$order_goods['price'],
							'quantity'=>$order_goods['quantity'],
							'is_anonymity'=>$order_goods['is_anonymity'],
							'created'=>$order_goods['pay_time']?$order_goods['pay_time']:$order_goods['created'],
							'source'=>$order_goods['source'],
							'sys'=>0,
						);

						DB::insert('order_trades', array_keys($insert))->values(array_values($insert))->execute();
						unset($insert);
						echo '>';
						$i++;
						$j++;
					}
					unset($order_goods_array);
				}
			}
			$iterator->next();
		}

		CLI::output("共插入 {$i} 条交易记录");
	}
}